package com.gsafety.libraryktx.widget

import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.webkit.WebResourceRequest
import android.webkit.WebView
import android.widget.LinearLayout
import androidx.fragment.app.Fragment
import com.gsafety.libraryktx.R
import com.just.agentweb.AgentWeb
import com.just.agentweb.WebViewClient


/**封装webview
 * @author : lj
 * @date : 2020/8/3 9:51
 */
class CommonWebView @JvmOverloads constructor(context: Context,
                                              attrs: AttributeSet? = null,
                                              defStyleAttr: Int = 0) : LinearLayout(context, attrs, defStyleAttr) {
    var mWebView: WebView? = null

    var linWeb: LinearLayout? = null

    init {
        initview(attrs)
    }


    private fun initview(attrs: AttributeSet?) {
        var view = LayoutInflater.from(context).inflate(R.layout.common_webview_layout, this)
        linWeb = view.findViewById(R.id.lin_web)
    }

   private fun setting(mAgentWeb:AgentWeb){
       var setting=mAgentWeb.agentWebSettings.webSettings
       setting.setSupportZoom(true)
       setting.builtInZoomControls=true//设置出现缩放工具
       setting.useWideViewPort=true//扩大比例的缩放
       setting.displayZoomControls=false//隐藏缩放控件
   }

    fun loadUrl(obj: Any,URL: String) {
        linWeb?.also {
            if(obj is Activity){
                var web=AgentWeb.with(obj)
                        .setAgentWebParent(it, LayoutParams(-1, -1))
                        .useDefaultIndicator() //进度条
                        .setWebViewClient(mWebViewClient)
                        .createAgentWeb()
                        .ready()
                        .go(URL)
                setting(web)
            }
            if(obj is Fragment){
                var web=AgentWeb.with(obj)
                        .setAgentWebParent(it, LayoutParams(-1, -1))
                        .useDefaultIndicator() //进度条
                        .setWebViewClient(mWebViewClient)
                        .createAgentWeb()
                        .ready()
                        .go(URL)
                setting(web)
            }
        }

    }

    private val mWebViewClient: WebViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
            return true
        }
    }
}